<?php

namespace Admin\Controller;

use Base\BackController;

class BhLabelController extends BackController {

    //用户列表
    public function index() {
        $this->user_model = M('bh_label');
        $this->status_arr= array(
            '0' => '无效',
            '1' => '有效'
        );
        // var_dump($_GET());die;
        $map=array();
        if($_GET['name']!=''&& $_GET['name']!=1){
            $map['name']=array('like', '%'.$_GET['name'].'%');
        }
        if($_GET['status']!=''){
             $map['status']=array('like', '%'.$_GET['status'].'%');
        }
        // var_dump($map);die;
        //任务总数
        $total = $this->user_model->where($map)->count();
        //每页条数
        $listRows = C('LIST_ROWS') > 0 ? C('LIST_ROWS') : 10;
        //实例化分页类
        $page = new \Admin\ORG\PageNew($total, $listRows, '');
        if ($total > $listRows) {
            $page->setConfig('theme', '%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END% %HEADER%');
        }
        $p = $page->show();
        $this->assign('_page', $p ? $p : '');     
        $dataList = $this->user_model->where($map)->order('eosi_bh_label.show_order desc, eosi_bh_label.update_time desc')->limit("$page->firstRow,$page->listRows")
        ->select();
        //数据处理
        foreach ($dataList as $k => $value){
            $cctime=$value['create_time'];
            // 状态
            if ($value['status'] == 1) {
                $value['status_str'] = "<span class=\"label label-sm label-success arrowed-in\" >" . $this->status_arr[$value['status']] . "</span>&nbsp;|&nbsp;&nbsp;&nbsp;<span class=\"hand icon-lock red bigger-125\" title=\"禁用它，前台不会显示\" style=\"cursor: pointer;\" index='" . $value['id'] . "' ></span>";
            }else{
                $value['status_str'] = "<span class=\"label label-sm label-info arrowed-in\">" . $this->status_arr[0] . "</span>&nbsp;|&nbsp;&nbsp;&nbsp;<span class=\"hand icon-unlock green bigger-125\" title=\"启用它，前台将会显示\"  style=\"cursor: pointer;\" index='" . $value['id'] . "' ></span>";
            }
            $value['create_time'] = date('Y-m-d H:i:s', $value['create_time']);
            $value['update_time'] = date('Y-m-d H:i:s', $value['update_time']);
            $value['img'] =  ic_getUploadImgFullPath(bhlabel,$value['img'],$cctime);
            // $value['choose_img'] =  ic_getUploadImgFullPath(bhtype,$value['choose_img'],$cctime);
            $dataList[$k] = $value;
        }

        $this->assign('name', $_GET['name']);
        $this->assign('status', $_GET['status']);
        // $this->assign('_listopt', $dataListopt);
        $this->assign('_list', $dataList);
        $this->assign('groupName', '造型类别管理 ');
        $this->assign('moduleName', '类别列表');
        $this->assign('actionName', '列表概览');
        $this->display();
    }
    // 状态修改
    public function status_change(){
        try {
            $type = I('type');
            $userid = I('id');
            if (empty($type) || empty($userid)) {
                $ajaxdata['info'] = '丢失参数';
                $ajaxdata['status'] = 200;
                $this->ajaxReturn($ajaxdata);
            }
            if ($type == '有效')
                $str = '启用用户';
            if ($type == '无效')
                $str = '禁用用户';
            $data = array();
            $data['id'] = $userid;
            if ($type == '有效') {
                $data['status'] = 0;
            }
            if ($type == '无效') {
                $data['status'] = 1;
            }
            $falg=M('bh_label')->save($data); 
            if(!$falg){
                $ajaxdata['info'] = '网络故障提交失败,请稍候再试';
                $ajaxdata['status'] = 200;
                $this->ajaxReturn($ajaxdata);
            }
            $ajaxdata['info'] = 'ok';
            $ajaxdata['status'] = 1;
            $this->ajaxReturn($ajaxdata);
        } catch (Exception $exc) {
            $ajaxdata['info'] = $exc->getMessage();
            $ajaxdata['status'] = 400;
            $this->ajaxReturn($ajaxdata);
        }
    }
    //编辑规则
        public function editRule() {
            $ruleid = I('id');
            if (empty($ruleid)) {
                $this->error('缺失主键');
            }
            $map = array();
            $map['eosi_bh_label.id'] = $ruleid;
            $data = M('bh_label')->where($map)->find();
            if (empty($data)) {
                $this->error('数据不存在');
            }
            $data['img'] =  ic_getUploadImgFullPath('bhlabel',$data['img'],$data['create_time']);
            $data['choose_img'] =  ic_getUploadImgFullPath('bhlabel',$data['choose_img'],$data['create_time']);
            $mapto=array();
            $mapto['id']=array('neq', '1');
            $this->new_type =M('bh_type');
            $dataListopt =$this->new_type->where($mapto)->select();
            $this->assign('_listopt', $dataListopt);
            // var_dump( $data);exits;
            $this->assign('data', $data);
            $this->assign('groupName', '造型类别管理 ');
            $this->assign('moduleName', '类别列表');
            $this->assign('actionName', '编辑类别');
            $this->display('BhLabel:editRule');
        }
    //更新规则
    public function updateRule() {
        try {
                $ruleid = I('id');
                if (empty($ruleid)) {
                    $this->error('缺失主键');
                }
                // var_dump(I());die;
                $name = I('name');
                $status = I('status');
                // $show_order = I('show_order');
                $map = array();
                $map['id'] = $ruleid;
                $show_order= I('show_order',100);
        
                $saveData = array();
                // $saveData['id'] = $ruleid;
                //perry 注释下面2句，在上传图片时已经实时更新表数据了，此处无需再更新
                // $saveData['img'] = $p_new_pic;
                // $saveData['sub_imgs'] = $sub_imgs;
                //end perry
                $saveData['name'] = $name;
                $saveData['status'] = $status;
                $saveData['update_time'] =time();
                $saveData['show_order'] = $show_order;
                // $saveData['show_order'] =$show_order;
                // var_dump($saveData);die;
                $flag = M('bh_label')->where($map)->save($saveData);
                if ($flag) {
                    $this->success('造型类别编辑成功,正在跳转请稍候……', '/Admin/BhLabel/index');
                } else {
                    $this->error('造型类别编辑失败，是否未做修改，如有修改请重试.');
                }
            }catch (Exception $exc) {
                    $ajaxdata['info'] = $exc->getMessage();
                    $ajaxdata['status'] = 400;
                    $this->ajaxReturn($ajaxdata);
            }
    }
    //上传单品图片
    public function uploadImg() {
        
       try {
            $id=I('id',false);
            $ctime=time();
            if(ic_isPosInt($id)){
                //是编辑的提交
                $map=array('id'=>$id);
                $exist=M('bh_label')->where($map)->find();
                if(!$exist){
                    echo "<script>parent.art.dialog.alert('" . "待更新的数据不存在，请刷新页面重试." . "');</script>";
                    exit;
                }
                $ctime=$exist['create_time'];
            }
            // import('@.ORG.UploadFileNew');
            //导入上传类
            $upload = new \Admin\ORG\UploadFileNew();
            //设置上传文件大小
            $upload->maxSize            = 100*1024*1024;
            //设置上传文件类型
            $upload->allowExts          = explode(',', 'jpg,gif,png,jpeg');
            //设置附件上传目录
            $upload->savePath           = ic_getUploadImgServerPath('bhlabel',$ctime);
            //设置需要生成缩略图，仅对图像文件有效
            $upload->thumb              = false;
            // 设置引用图片类库包路径
            $upload->imageClassPath     = 'Think.ImageNew';
            //设置需要生成缩略图的文件后缀
            // $upload->thumbPrefix        = 'm_,s_';  //生产2张缩略图
            //设置缩略图最大宽度
            $upload->thumbMaxWidth      = '700,200';
            //设置缩略图最大高度
            $upload->thumbMaxHeight     = '850,243';
            //设置上传文件规则
            $upload->saveRule           = 'uniqid';
            //删除原图
            $upload->thumbRemoveOrigin  = false;
            if (!$upload->upload()) {
                //捕获上传异常
                //$this->error($upload->getErrorMsg());
                //echo ($upload->getErrorMsg());
            } else {
                //取得成功上传的文件信息
                $uploadList = $upload->getUploadFileInfo();
                //试着删除之前上传的旧图片
                $this->deleteOld();
                //保存当前图片信息到session
                $this->saveOldFIleSession($uploadList,$ctime);
                foreach ($uploadList as $key => $value) {
                    echo "<script>
                    parent.document.getElementById('img').style.display='';
                    parent.document.getElementById('img').src='" . ic_getUploadImgFullPath('bhlabel',$value['savename'],$ctime) . "';
                    parent.document.getElementById('p_new_pic').value='" . $value['savename'] . "';
                    </script>";
                    //如果是编辑页提交，直接保存数据表，否则会造成旧图片成为垃圾图片无法删除
                    if($exist){
                        $oldfilePath=ic_getUploadImgServerPath('bhlabel',$exist['create_time']);
                        $this->delMulti($oldfilePath,$exist['img']);
                        $data=array('img'=>$value['savename'],'update_time'=>time());
                        M('bh_label')->where($map)->save($data);
                    }
                }   
            }
        }catch (Exception $exc) {
            //返回失败信息
            echo "<script>parent.art.dialog.alert('" . $exc->getMessage() . "');</script>";
            exit;
        }
    }
 //上传选中图片
    public function uuploadImg() {
        
       try {
            $id=I('id',false);
            $ctime=time();
            if(ic_isPosInt($id)){
                //是编辑的提交
                $map=array('id'=>$id);
                $exist=M('bh_type')->where($map)->find();
                if(!$exist){
                    echo "<script>parent.art.dialog.alert('" . "待更新的数据不存在，请刷新页面重试." . "');</script>";
                    exit;
                }
                $ctime=$exist['create_time'];
            }
            // import('@.ORG.UploadFileNew');
            //导入上传类
            $upload = new \Admin\ORG\UploadFileNew();
            //设置上传文件大小
            $upload->maxSize            = 100*1024*1024;
            //设置上传文件类型
            $upload->allowExts          = explode(',', 'jpg,gif,png,jpeg');
            //设置附件上传目录
            $upload->savePath           = ic_getUploadImgServerPath('bhlabel',$ctime);
            //设置需要生成缩略图，仅对图像文件有效
            $upload->thumb              = true;
            // 设置引用图片类库包路径
            $upload->imageClassPath     = 'Think.ImageNew';
            //设置需要生成缩略图的文件后缀
            $upload->thumbPrefix        = 'm_,s_';  //生产2张缩略图
            //设置缩略图最大宽度
            $upload->thumbMaxWidth      = '700,200';
            //设置缩略图最大高度
            $upload->thumbMaxHeight     = '850,243';
            //设置上传文件规则
            $upload->saveRule           = 'uniqid';
            //删除原图
            $upload->thumbRemoveOrigin  = false;
            if (!$upload->upload()) {
                //捕获上传异常
                //$this->error($upload->getErrorMsg());
                //echo ($upload->getErrorMsg());
            } else {
                //取得成功上传的文件信息
                $uploadList = $upload->getUploadFileInfo();
                //试着删除之前上传的旧图片
                $this->deleteOld();
                //保存当前图片信息到session
                $this->saveOldFIleSession($uploadList,$ctime);
                foreach ($uploadList as $key => $value) {
                    echo "<script>
                    parent.document.getElementById('choose_img').style.display='';
                    parent.document.getElementById('choose_img').src='" . ic_getUploadImgFullPath('bhlabel',$value['savename'],$ctime) . "';
                    parent.document.getElementById('pp_new_pic').value='" . $value['savename'] . "';
                    </script>";
                    //如果是编辑页提交，直接保存数据表，否则会造成旧图片成为垃圾图片无法删除
                    if($exist){
                        $oldfilePath=ic_getUploadImgServerPath('bhlabel',$exist['create_time']);
                        $this->delMulti($oldfilePath,$exist['choose_img']);
                        $data=array('choose_img'=>$value['savename'],'update_time'=>time());
                        M('bh_type')->where($map)->save($data);
                    }
                }   
            }
        }catch (Exception $exc) {
            //返回失败信息
            echo "<script>parent.art.dialog.alert('" . $exc->getMessage() . "');</script>";
            exit;
        }
    }

    //上传商品关联图片
    public function upload() {
        try {
            $id=I('id',false);
            $ctime=time();
            if(ic_isPosInt($id)){
                //是编辑的提交
                $map=array('id'=>$id);
                $exist=M('bh_closet_commodity')->where($map)->find();
                if(!$exist){
                    echo "<script>parent.art.dialog.alert('" . "待更新的数据不存在，请刷新页面重试." . "');</script>";
                    exit;
                }
                $ctime=$exist['create_time'];
            }
            // import('@.ORG.UploadFileNew');
            //导入上传类
            $upload = new \Admin\ORG\UploadFileNew();
            //设置上传文件大小
            $upload->maxSize            = 100*1024*1024;
            //设置上传文件类型
            $upload->allowExts          = explode(',', 'jpg,gif,png,jpeg');
            //设置附件上传目录
            $upload->savePath           = ic_getUploadImgServerPath('commodity',$ctime);
            //设置需要生成缩略图，仅对图像文件有效
            $upload->thumb              = true;
            // 设置引用图片类库包路径
            $upload->imageClassPath     = 'Think.ImageNew';
            //设置需要生成缩略图的文件后缀
            $upload->thumbPrefix        = 'm_,s_';  //生产2张缩略图
            //设置缩略图最大宽度
            $upload->thumbMaxWidth      = '700,200';
            //设置缩略图最大高度
            $upload->thumbMaxHeight     = '850,243';
            //设置上传文件规则
            $upload->saveRule           = 'uniqid';
            //删除原图
            $upload->thumbRemoveOrigin  = false;
            if (!$upload->upload()) {
                //捕获上传异常
                //$this->error($upload->getErrorMsg());
                //echo ($upload->getErrorMsg());
            } else {
                //取得成功上传的文件信息
                $uploadList = $upload->getUploadFileInfo();
                $img_arr=array();
                foreach ($uploadList as $key => $value) {
                    $img_arr[]=$value['savename'];
                }
                //试着删除之前上传的旧图片
                $this->deleteOld();
                //保存当前图片信息到session
                $this->saveOldFIleSession($uploadList,$ctime);
                $ajaxdata['info'] = implode(',', $img_arr);
                //如果是编辑页提交，直接保存数据表，否则会造成旧图片成为垃圾图片无法删除
                if($exist){
                    $oldfilePath=ic_getUploadImgServerPath('commodity',$exist['create_time']);
                    $tmparr=explode(',',$exist['sub_imgs']);
                    foreach ($tmparr as $key => $value) {
                        $this->delMulti($oldfilePath,$value);
                    }
                    $data=array('sub_imgs'=>$ajaxdata['info'],'update_time'=>time());
                    M('bh_closet_commodity')->where($map)->save($data);
                }
                $ajaxdata['status'] = 1;
                $this->ajaxReturn($ajaxdata);
            }
        }catch (Exception $exc) {
            $ajaxdata['info'] = $exc->getMessage();
            $ajaxdata['status'] = 400;
            $this->ajaxReturn($ajaxdata);
        }
    }

    //接受一个参数，从服务器上删除一张图片
    public function uploadDelete(){
        $exist=false;
        $skey=I('session_key',false);
        if($skey===false){
            $id=I('id',false);
            if(!ic_isPosInt($id)){
                return;
            }
            else {
                $map=array('id'=>$id);
                $exist=M('bh_type')->where($map)->find();
                if(!$exist){
                    return;
                }
                $ctime=$exist['create_time'];
            }
        }
        else {
            $ctime=$_SESSION[$skey."_time"];
        }

        $delName=I('realName',false);
        if($delName===false){
            return;
        }
        $serverPath=ic_getUploadImgServerPath("bhtype",$ctime);
        $this->delMulti($serverPath,$delName);
        if($exist){
            //是来自编辑页面的删除，需要实时保存到数据表
            $oldNames=explode(",", $exist['sub_imgs']);
            $newNames=array();
            foreach ($oldNames as $key => $value) {
                if($value!=$delName){
                    $newNames[]=$value;
                }
            }
            $newNames=implode(",", $newNames);
            $data['update_time']=time();
            $data['sub_imgs'] = $newNames;
            M('bh_type')->where($map)->save($data);
        }
    }

    private function delMulti($serverPath,$delName){
        @unlink($serverPath.$delName);
        @unlink($serverPath."m_".$delName);
        @unlink($serverPath."s_".$delName);
    }

    //从session取得旧图片信息并删除
    private function deleteOld(){
        $skey=I('session_key',false);
        if($skey===false){
            return;
        }
        $oldFiles=$_SESSION[$skey];
        if(!$oldFiles){
            return;
        }
        foreach ($oldFiles as $key => $value) {
            $serverPath=ic_getUploadImgServerPath("commodity",$_SESSION[$skey."_time"]);
            // @unlink($serverPath.$value['savename']);
            // @unlink($serverPath."m_".$value['savename']);
            // @unlink($serverPath."s_".$value['savename']);
            $this->delMulti($serverPath,$value['savename']);
        }
    }

    private function saveOldFIleSession($arr,$ctime){
        $skey=I('session_key',false);
        if($skey===false){
            return;
        }
        $_SESSION[$skey]=$arr;
        $_SESSION[$skey."_time"]=$ctime;
    }

    public function getMillisecond() {
        list($t1, $t2) = explode(' ', microtime());
        return (float) sprintf('%.0f', (floatval($t1) + floatval($t2)) * 1000);
    }
    //添加规则
    public function addRule() {
        $this->assign('groupName', '造型类别管理 ');
        $this->assign('moduleName', '类别列表');
        $this->assign('actionName', '添加类别');
        $this->display('BhLabel:addRule');
    }
    //保存规则
    public function insertRule() {
        // var_dump(I());die;
        // $uid = 999;
        // var_dump($uid);
        $name = I('name');
        $p_new_pic = I('p_new_pic');
        // $pp_new_pic = I('pp_new_pic');
        $status = I('status');
        // $memo = I('memo');
        $show_order= I('show_order',100);

        $saveData = array();
        $saveData['name'] = $name;
        $saveData['img'] = $p_new_pic;
        // $saveData['choose_img'] = $pp_new_pic;
        $saveData['status'] = $status;
        // $saveData['show_order'] = $memo;
        $saveData['create_time'] = time();
        // var_dump($saveData);die;
        $saveData['show_order'] = $show_order;

        $flag = M('bh_label')->add($saveData);
        if ($flag) {
            $this->success('添加成功', __CONTROLLER__ . '/index');
        } else {
            $this->error('添加失败');
        }
    }
    //删除规则
    public function deleteRule() {
        $ruleid = I('id');
        if (empty($ruleid)) {
            $this->error('缺失主键');
        }
        //主键为1的代表所有类型，不能删除
        if($ruleid==1){
            $this->error('类别“所有”是系统默认类别,只能编辑不能删除哦.');
        }
        //删除规则表
        $flag = M('bh_label')->where("id={$ruleid}")->delete();
        if ($flag) {
            $this->success('造型类别删除成功', __CONTROLLER__ . '/index');
        } else {
            $this->error('造型类别删除失败');
        }
    }
    // 非管理员用户------------------------------------------------------------------------------
     //用户列表
    public function closer() {
        $this->user_model = M('bh_closet_commodity');
        $join = 'left join eosi_weixin_user ON eosi_bh_closet_commodity.uid = eosi_weixin_user.id';
        $joinad ='left join eosi_bh_type ON eosi_bh_closet_commodity.type = eosi_bh_type.id';
        $this->status_arr= array(
            '0' => '无效',
            '1' => '有效'
        );
        $map=array();
        if($_GET['nickname']!=''){
            $map['eosi_weixin_user.nickname']=array('like', '%'.$_GET['nickname'].'%');
        }
        if($_GET['aname']!=''){
             $map['eosi_bh_closet_commodity.name']=array('like', '%'.$_GET['aname'].'%');
        }
        if($_GET['bname']!='' && $_GET['bname']!= 1){
             $map['eosi_bh_type.id']=$_GET['bname'];
        }
        if($_GET['memo']!=''){
             $map['eosi_bh_closet_commodity.memo']=array('like', '%'.$_GET['memo'].'%');
        }

        $map['eosi_bh_closet_commodity.uid']=array('neq', '999');;
        // $map['eosi_bh_closet_commodity.uid'] !=999;
        // var_dump($map);exit;    
        //任务总数
        $total = $this->user_model->join($join)->join($joinad)->where($map)->count();
        //每页条数
        $listRows = C('LIST_ROWS') > 0 ? C('LIST_ROWS') : 10;
        //实例化分页类
        $page = new \Admin\ORG\PageNew($total, $listRows, '');
        if ($total > $listRows) {
            $page->setConfig('theme', '%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END% %HEADER%');
        }
        $p = $page->show();
        $this->assign('_page', $p ? $p : '');     
        $ab ='eosi_bh_closet_commodity.img as aimg,eosi_bh_type.img as bimg,
                eosi_bh_closet_commodity.name as aname,eosi_bh_type.name as bname,
                eosi_weixin_user.nickname,eosi_bh_closet_commodity.*';
        $dataList = $this->user_model->join($join)->join($joinad)->where($map)->order('eosi_bh_closet_commodity.id desc')->limit("$page->firstRow,$page->listRows")->Field($ab)->select();
        // dump($dataList);
        $this->new_type =M('bh_type');
        $dataListopt =$this->new_type->select();
        //数据处理
        foreach ($dataList as $k => $value){
            $cctime=$value['create_time'];
            //状态
            if ($value['status'] == 1) {
                $value['status_str'] = "<span class=\"label label-sm label-success arrowed-in\" >" . $this->status_arr[$value['status']] . "</span>&nbsp;|&nbsp;&nbsp;&nbsp;<span class=\"hand icon-lock red bigger-125\" title=\"禁用\" style=\"cursor: pointer;\" index='" . $value['id'] . "' ></span>";
            }else{
                $value['status_str'] = "<span class=\"label label-sm label-info arrowed-in\">" . $this->status_arr[0] . "</span>&nbsp;|&nbsp;&nbsp;&nbsp;<span class=\"hand icon-unlock green bigger-125\" title=\"启用\"  style=\"cursor: pointer;\" index='" . $value['id'] . "' ></span>";
            }
            $value['create_time'] = date('Y-m-d H:i:s', $value['create_time']);
            $value['dh_date'] = date('Y-m-d ', $value['dh_date']);
            $value['dh_date'] = explode('-', $value['dh_date']);
            $c = $value['dh_date'][0];
            $a = $value['dh_date'][1];
            $a = preg_replace('/^0/', '', $a);
            $b = $value['dh_date'][2];
            $b = preg_replace('/^0/', '', $b);
            $value['dh_date'] =$c.'.'.$a.'.'.$b;
            // $map['eosi_bh_calendar.year']=array('like',$_GET['bname'][0]);
            // $map['eosi_bh_calendar.month']=array('like',$a);
            // $map['eosi_bh_calendar.day']=array('like',$b);

            $value['img'] =  ic_getUploadImgFullPath(commodity,$value['aimg'],$cctime);
            
            $dataList[$k] = $value;
            $imgchild = array();
            if(ic_checkUnEmpty($value['sub_imgs'])){
                $value['sub_imgs'] =explode(',',$value['sub_imgs']); 
                foreach ($value['sub_imgs'] as $key => $v) {
                    $v =  ic_getUploadImgFullPath('commodity',$v,$cctime);
                    $imgchild[$key] = $v;
                }
            }
            $dataList[$k]['sub_imgs_arr'] = $imgchild;
        }
        
        $this->assign('_listopt', $dataListopt);
        $this->assign('_list', $dataList);
        $this->assign('bname_id', $_GET['bname']);
        $this->assign('nickname', $_GET['nickname']);
        $this->assign('aname', $_GET['aname']);
        $this->assign('memo', $_GET['memo']);
        $this->assign('groupName', '商品管理');
        $this->assign('moduleName', '商品列表');
        $this->assign('actionName', '商品概览');
        // $this->assign('nickname',$array['nickname']);
        $this->display();
    }
}
